package cn.iocoder.yudao.module.shop.convert.opthistory;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.blog.controller.admin.jiutag.vo.BlogJiuTagRespVO;
import cn.iocoder.yudao.module.blog.convert.jiutag.BlogJiuTagConvert;
import cn.iocoder.yudao.module.blog.dal.dataobject.jiutag.BlogJiuTagDO;
import cn.iocoder.yudao.module.shop.controller.admin.opthistory.vo.ShopOptHistoryCreateReqVO;
import cn.iocoder.yudao.module.shop.controller.admin.opthistory.vo.ShopOptHistoryRespVO;
import cn.iocoder.yudao.module.shop.controller.admin.order.vo.ShopOrderRespVO;
import cn.iocoder.yudao.module.shop.dal.dataobject.opthistory.ShopOptHistoryDO;
import jodd.util.StringUtil;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Mapper
public interface ShopOptHistoryConvert {
    ShopOptHistoryConvert INSTANCE = Mappers.getMapper(ShopOptHistoryConvert.class);

    ShopOptHistoryRespVO convert(ShopOptHistoryDO bean);

    ShopOptHistoryDO convert(ShopOptHistoryCreateReqVO bean);

    default ShopOptHistoryRespVO convert(ShopOptHistoryDO bean, List<BlogJiuTagDO> tagList){
        ShopOptHistoryRespVO shopOptHistoryRespVO = convert(bean);

        shopOptHistoryRespVO.setTagList(BlogJiuTagConvert.INSTANCE.convertList(tagList));

        return shopOptHistoryRespVO;
    }

    default PageResult<ShopOptHistoryRespVO> convertPage(PageResult<ShopOptHistoryDO> pageResult, List<BlogJiuTagDO> tagList){
        Map<Long, BlogJiuTagDO> tagMap = new HashMap<>();
        for(int i = 0; i<tagList.size(); i++){
            tagMap.put(tagList.get(i).getId(), tagList.get(i));
        }

        List<ShopOptHistoryRespVO> respVoList = new ArrayList<>();
        for(int i = 0; i<pageResult.getList().size(); i++) {
            ShopOptHistoryDO bean = pageResult.getList().get(i);
            List<BlogJiuTagDO> tagDOList = new ArrayList<>();

            if (bean.getTags() != null && StringUtil.isNotEmpty(bean.getTags())) {
                String[] ids = bean.getTags().split(";");
                for (int j = 0; j < ids.length; j++) {
                    tagDOList.add(tagMap.get(Long.parseLong(ids[i])));
                }
            }

            respVoList.add(convert(bean, tagDOList));
        }

        PageResult<ShopOptHistoryRespVO> newPageResult = new PageResult<ShopOptHistoryRespVO>();
        newPageResult.setList(respVoList);
        newPageResult.setTotal(pageResult.getTotal());

        return newPageResult;
    }
}
